package com.itheima.web;

import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("来了一个GET请求...");
        //1. 获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String checkCode = req.getParameter("checkCode");
        //1.1 比较验证码
        String code = (String) req.getSession().getAttribute("code");
        if(!code.equalsIgnoreCase(checkCode)){
            req.setAttribute("register_msg" , "验证码错误！");
            req.getRequestDispatcher("register.jsp").forward(req ,resp);
            return ;
        }
        //2. 调用service
        UserService us = new UserService();
        int row = us.register(username, password);
        //3. 判断结果：
        if(row == 0){
             //3.1 注册失败 返回失败的原因...
            //req.getSession().setAttribute("register_msg" , "注册失败！");
            //resp.sendRedirect("register.jsp");
            req.setAttribute("register_msg" , "注册失败！");
            req.getRequestDispatcher("register.jsp").forward(req ,resp);
        }else if( row > 0 ){
            //3.2 注册成功 就跳转到登录页面
            resp.sendRedirect("login.jsp");
        }else {
            //3.3 用户名已存在
//            req.getSession().setAttribute("register_msg" , "用户名已被占用!");
//            resp.sendRedirect("register.jsp");
            req.setAttribute("register_msg" , "用户名已被占用！");
            req.getRequestDispatcher("register.jsp").forward(req ,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("来了一个POST请求...");
        this.doGet(req, resp);
    }
}
